package com.dreammakerteam.frameworkdemo.qzhj.controller;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.dreammakerteam.frameworkdemo.base.controller.DBaseController;
import com.dreammakerteam.frameworkdemo.base.domain.DBaseException;
import com.dreammakerteam.frameworkdemo.base.utils.FileUtil;
import com.dreammakerteam.frameworkdemo.qzhj.domain.DQzhjProductDo;
import com.dreammakerteam.frameworkdemo.qzhj.domain.DQzhjProductHistoryDo;
import com.dreammakerteam.frameworkdemo.qzhj.domain.DQzhjProductTypeDo;
import com.dreammakerteam.frameworkdemo.qzhj.service.DQProductService;
import com.dreammakerteam.frameworkdemo.qzhj.service.DQzhjProductAttachmentService;
import com.dreammakerteam.frameworkdemo.qzhj.service.DQzhjProductHistoryService;
import com.dreammakerteam.frameworkdemo.qzhj.service.DQzhjProductTypeService;
import com.dreammakerteam.frameworkdemo.base.domain.DAreaDo;
import com.dreammakerteam.frameworkdemo.base.service.DAreaService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 清真货架主入口
 * Created by ty850 on 2017/10/10.
 */
@Controller
@RequestMapping("/qzhj")
public class DQzhjController extends DBaseController {

    @Resource
    private DQProductService dqProductService;

    @Resource
    private DQzhjProductAttachmentService dQzhjProductAttachmentService;

    @Resource
    private DQzhjProductTypeService dQzhjProductTypeService;

    @Resource
    private DAreaService dAreaService;

    @Resource
    private DQzhjProductHistoryService dQzhjProductHistoryService;


    @RequestMapping
    @RequiresRoles("aaaa")
    public String index() {
        return "qzhj/index";
    }



    @GetMapping("/prod/add")
    public String prodAdd(Model model, HttpSession session) {
        // 获取所有类型

        List<DQzhjProductTypeDo> typeDos = dQzhjProductTypeService.selectList(null);


        List<DQzhjProductTypeDo> typeKeys = new ArrayList<>();
        HashMap<String, List<DQzhjProductTypeDo>> typeValues = new HashMap<>();

        typeDos.forEach(dQzhjProductTypeDo -> {
            if (dQzhjProductTypeDo.getParentId() == null)
                typeKeys.add(dQzhjProductTypeDo);
            else {
                List<DQzhjProductTypeDo> typeValue = typeValues.get(dQzhjProductTypeDo.getParentId().toString());
                if (typeValue == null) {
                    typeValue = new ArrayList<>();
                    typeValues.put(dQzhjProductTypeDo.getParentId().toString(), typeValue);
                }
                typeValue.add(dQzhjProductTypeDo);
            }
        });

        model.addAttribute("typeKeys", typeKeys);
        model.addAttribute("typeValues", typeValues);

        // 唯一标识
        String uuid = IdWorker.get32UUID();
        session.setAttribute("UUID", uuid);
        model.addAttribute("token", uuid);


        Object err = session.getAttribute("err");
        if (err != null) {
            model.addAttribute("err", err);
            session.removeAttribute("err");
        }
        Object it = session.getAttribute("it");
        if (it != null) {
            model.addAttribute("it", it);
            session.removeAttribute("it");
        }


        return "qzhj/prod/add";
    }

    @PostMapping("/prod/add")
    public String prodPAdd(HttpSession session, DQzhjProductDo prod, @RequestParam("images") MultipartFile[] multipartFile, @RequestParam(required = false) String token, @SessionAttribute(required = false) String UUID) throws IOException, SolrServerException {
        try {
            if (StringUtils.isEmpty(token) || !token.equals(UUID))
                throw new DBaseException("请不要重复提交（这个判断的目的是为了防止重复提交，当然不仅仅是重复提交才会出现这个错误）");
            dqProductService.add(prod, FileUtil.uploadFiles(multipartFile));
            session.setAttribute("title", "成功");
            session.setAttribute("msg", "商品添加成功");
            return "redirect:/qzhj/prod/add/result";
        } catch (Exception e) {
            session.setAttribute("err", e.getMessage());
            session.setAttribute("it", prod);
            return "redirect:/qzhj/prod/add";
        }
    }
    @RequestMapping("/prod/add/result")
    public String success(Model model, HttpSession session) {
        Object title = session.getAttribute("title");
        if (title != null) {
            model.addAttribute("title", title);
            session.removeAttribute("title");
        }
        Object msg = session.getAttribute("msg");
        if (msg != null) {
            model.addAttribute("msg", msg);
            session.removeAttribute("msg");
        }
        return "qzhj/prod/msg";
    }




    @GetMapping("/prod/info")
    public String prodInfo(Long prodId, Model model) {

        // 获取实体
        DQzhjProductDo product = dqProductService.getMapper().selectById(prodId);
        if (product == null) {
            model.addAttribute("title", "错误");
            model.addAttribute("msg", "指定的商品不存在");
            return "qzhj/prod/msg";
        }
        model.addAttribute("it", product);

        // 获取图片
        String[] attachments = dQzhjProductAttachmentService.getMapper().getProductAttachments(prodId);
        model.addAttribute("imgs", attachments);


        // 获取地区
        Long provinceId = product.getProvinceId();
        if (provinceId != null) {
            DAreaDo dAreaDo = dAreaService.getMapper().selectById(provinceId);
            model.addAttribute("province", dAreaDo.getDaName());
        }
        Long cityId = product.getCityId();
        if (cityId != null) {
            DAreaDo dAreaDo = dAreaService.getMapper().selectById(cityId);
            model.addAttribute("city", dAreaDo.getDaName());
        }
        Long areaId = product.getAreaId();
        if (areaId != null) {
            DAreaDo dAreaDo = dAreaService.getMapper().selectById(areaId);
            model.addAttribute("area", dAreaDo.getDaName());
        }
        // 获取类型
        DQzhjProductTypeDo dQzhjProductTypeDo = dQzhjProductTypeService.selectById(product.getTypeId());
        model.addAttribute("typeName", dQzhjProductTypeDo.getName());


        // 产品动态
        DQzhjProductHistoryDo[] historys = dQzhjProductHistoryService.get(prodId);
        model.addAttribute("historys", historys);

        return "qzhj/prod/info";
    }

}
